package com.west.common.share;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.west.common.app.AppOperator;
import com.west.common.base.adapter.BaseRecyclerAdapter;
import com.west.common.common.R;
import com.west.common.helper.AccountHelper;
import com.west.common.uitils.DialogHelper;
import com.west.common.uitils.StreamUtil;
import com.west.common.widget.SimplexToast;
import com.west.common.widget.dialog.BottomDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;


@SuppressWarnings("all")
public class ShareDialog extends BottomDialog implements OpenBuilder.Callback,
        DialogInterface.OnCancelListener, DialogInterface.OnDismissListener {
    private Activity mActivity;
    private ProgressDialog mDialog;
    private Share mShare;
    private boolean isOnlyBitmap;
    private boolean mSuccess = false;
    private TextView mTvCode;

    public ShareDialog(@NonNull Activity activity) {
        super(activity, true);
        this.mActivity = activity;
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View contentView = inflater.inflate(R.layout.dialog_share_main, null, false);
        RecyclerView shareRecycle = (RecyclerView) contentView.findViewById(R.id.share_recycler);
        mTvCode = contentView.findViewById(R.id.tv_invite_code);
        try {
            mTvCode.setText(AccountHelper.getUser().getInviteCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
        contentView.findViewById(R.id.iv_refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mListener != null){
                    mListener.refresh();
                }
            }
        });
        final ShareActionAdapter adapter = new ShareActionAdapter(activity);
        adapter.addAll(getAdapterData());
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, long itemId) {
                ShareDialog.this.onItemClick(position, adapter.getItem(position));
            }
        });
        shareRecycle.setAdapter(adapter);
        shareRecycle.setItemAnimator(new DefaultItemAnimator());
        shareRecycle.setLayoutManager(new GridLayoutManager(getContext(), 4));
        setContentView(contentView);
        setOnCancelListener(this);
        setOnDismissListener(this);
        mShare = new Share();
        mShare.setAppName("试用");
    }

    public ShareDialog(@NonNull Activity activity, String id) {
        this(activity);
        this.mActivity = activity;
        if (TextUtils.isEmpty(id)){
            isOnlyBitmap = true;
        }
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View contentView = inflater.inflate(R.layout.dialog_share_main, null, false);
        RecyclerView shareRecycle = (RecyclerView) contentView.findViewById(R.id.share_recycler);
        final ShareActionAdapter adapter = new ShareActionAdapter(activity);
        adapter.addAll(getAdapterData());
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, long itemId) {
                ShareDialog.this.onItemClick(position, adapter.getItem(position));
            }
        });
        shareRecycle.setAdapter(adapter);
        shareRecycle.setItemAnimator(new DefaultItemAnimator());
        shareRecycle.setLayoutManager(new GridLayoutManager(getContext(), 4));
        setContentView(contentView);
        setOnCancelListener(this);
        setOnDismissListener(this);
        mShare = new Share();
        mShare.setAppName("试用");
    }

    public void setCode(String code){
        if(mTvCode != null){
            mTvCode.setText(String.format("我的邀请码：%s", code));
        }
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        hideWaitDialog();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        hideWaitDialog();
    }

    private List<ShareItem> getAdapterData() {
        List<ShareItem> shareActions = new ArrayList<>();

        //0.微信
        shareActions.add(new ShareItem(R.mipmap.ic_login_3party_wechat, R.string.platform_wechat));
        //1.QQ
        shareActions.add(new ShareItem(R.mipmap.ic_login_3party_qq, R.string.platform_qq));
        //2.链接
        shareActions.add(new ShareItem(R.mipmap.ic_invite_link, R.string.platform_link));
        //3.二维码邀请
        shareActions.add(new ShareItem(R.mipmap.ic_invite_qrcode, R.string.platform_barcode));

        return shareActions;
    }

    public ShareDialog with() {
        mShare.setAppShareIcon(R.mipmap.ic_launcher);
        if (mShare.getBitmapResID() == 0)
            mShare.setBitmapResID(R.mipmap.ic_launcher);
        return this;
    }

    public ShareDialog title(String title) {
        mShare.setTitle(title);
        return this;
    }

    public ShareDialog summary(String summary) {
        mShare.setSummary(summary);
        return this;
    }

    public ShareDialog content(String content) {
        mShare.setContent(content);
        summary(content);
        description(content);
        return this;
    }

    public ShareDialog description(String description) {
        mShare.setDescription(description);
        return this;
    }

    public ShareDialog url(String url) {
        mShare.setUrl(url);
        return this;
    }

    public ShareDialog bitmapResID(int bitmapResID) {
        mShare.setBitmapResID(bitmapResID);
        return this;
    }

    public ShareDialog bitmap(Bitmap bitmap) {
        mShare.setThumbBitmap(bitmap);
        return this;
    }

    public ShareDialog imageUrl(final String imageUrl) {
        mShare.setImageUrl(imageUrl);

        if (!TextUtils.isEmpty(imageUrl)) {
            AppOperator.runOnThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Bitmap thumbBitmap = Glide.with(getContext())
                                .asBitmap()
                                .load(imageUrl).submit(100, 100).get();
                        //为微博和微信加入分享的详情icon

                        mShare.setThumbBitmap(thumbBitmap);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        return this;
    }

    public Share getShare() {
        return mShare;
    }

    @Override
    public void onFailed() {

    }

    @Override
    public void onSuccess(boolean success) {
        this.mSuccess = success;
    }

    public void alert(){
        if(mSuccess){
            SimplexToast.show("分享成功!");
        }
        mSuccess = false;
    }

    public void onItemClick(int position, ShareItem item) {
        Share share = getShare();
        switch (position) {
            //微信会话
            case 0:
                if(mListener != null){
                    mListener.wechat();
                }
                break;
            //QQ
            case 1:
                if(mListener != null){
                    mListener.qq();
                }
                break;
            case 2:
                if(mListener != null){
                    mListener.link();
                }
                break;
            case 3:
                if(mListener != null){
                    mListener.qr();
                }
                break;
        }
    }

    public static void saveShare(Activity activity, Bitmap bitmap) {
        FileOutputStream os = null;
        String url = null;
        try {
            File file = new File(url = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .getAbsolutePath() + File.separator + "黄河影视/");
            if (!file.exists())
                file.mkdirs();
            url = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .getAbsolutePath() + File.separator + "黄河影视/" +
                    System.currentTimeMillis() + ".jpg";
            os = new FileOutputStream(url);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bitmap != null && !bitmap.isRecycled())
                bitmap.recycle();
            StreamUtil.close(os);
            if (!TextUtils.isEmpty(url)) {
                Uri uri = Uri.fromFile(new File(url));
                activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                SimplexToast.show(activity,"保存成功");
            }
        }
    }

    private void hideWaitDialog() {
        ProgressDialog dialog = mDialog;
        if (dialog != null) {
            mDialog = null;
            try {
                dialog.cancel();
                // dialog.dismiss();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    private ProgressDialog showWaitDialog(@StringRes int messageId) {
        if (mDialog == null) {
            mDialog = DialogHelper.getProgressDialog(mActivity);
        }
        mDialog.setMessage(mActivity.getResources().getString(messageId));
        mDialog.show();
        return mDialog;
    }

    public void cancelLoading() {
        if (this != null && this.isShowing()) {
            this.cancel();
            this.dismiss();
            //mAlertDialog.dismiss();
        }
    }

    private void shareSystemImage(String url) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        Uri uri = FileProvider.getUriForFile(mActivity, "com.west.common.tryout.provider", new File(url));
        shareIntent.setType("image/*");
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
//        shareIntent.putExtra(Intent.EXTRA_TEXT, title);
        mActivity.startActivity(Intent.createChooser(shareIntent, "分享图片"));
    }

    private void showSystemShareOption(final String title, final String url) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "分享：" + title);
        intent.putExtra(Intent.EXTRA_TEXT, title + " " + url);
        getContext().startActivity(Intent.createChooser(intent, "选择分享"));
    }

    private class ShareActionAdapter extends BaseRecyclerAdapter<ShareItem> {

        ShareActionAdapter(Context context) {
            super(context, NEITHER);
        }

        @Override
        protected RecyclerView.ViewHolder onCreateDefaultViewHolder(ViewGroup parent, int type) {
            return new ShareViewHolder(LayoutInflater.from(mActivity).inflate(R.layout.dialog_share_item,
                    parent, false));
        }

        @Override
        protected void onBindDefaultViewHolder(RecyclerView.ViewHolder holder, ShareItem item, int position) {
            ShareViewHolder h = (ShareViewHolder) holder;
            h.mIvIcon.setImageResource(item.iconId);
            h.mTvName.setText(item.nameId);
        }
    }

    static class ShareViewHolder extends RecyclerView.ViewHolder {
        ImageView mIvIcon;
        TextView mTvName;

        public ShareViewHolder(View itemView) {
            super(itemView);
            mIvIcon = itemView.findViewById(R.id.share_icon);
            mTvName = itemView.findViewById(R.id.share_name);
        }
    }

    private static class ShareItem {
        int iconId;
        int nameId;

        ShareItem(int iconId, int nameId) {
            this.iconId = iconId;
            this.nameId = nameId;
        }
    }

    public void hideProgressDialog() {
        if (mDialog == null)
            return;
        mDialog.dismiss();
    }

    private ShareDialogListener mListener;

    public void setmListener(ShareDialogListener mListener) {
        this.mListener = mListener;
    }

    public interface ShareDialogListener{
        void wechat();
        void qq();
        void qr();
        void link();
        void refresh();
    }


}
